package com.hsck.order.kds.base.utils;

import com.blankj.utilcode.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Desc:
 * @author: xl
 * @Time: 2022/7/8 17:47
 * @Copyright:
 */
public class ListUtils {

    /**
     * 按照list 分割成多个list
     * @author:xl
     * @Time: 2021/8/26 10:06
     * @param mlist 原list
     * @param size 按数量分割
     * @return java.util.List<java.util.List<T>>
     */
    public static  <T>  List<List<T>> splitList(List<T> mlist, Integer num){
        if(CollectionUtils.isEmpty(mlist)||num<1){
            return null;
        }
        List<List<T>> batchList=new ArrayList<>();
        List<T> newList=new ArrayList<T>();;
        for(int i = 0; i<mlist.size();i++){
            List<T> s1=new ArrayList<>();
            T v1 = mlist.get(i);
            newList.add(v1);
            if((((i+1)%num == 0) )|| (i == (mlist.size()-1))){
                s1.addAll(newList);
                batchList.add(s1);
                newList = new ArrayList<T>();
            }
        }
        return batchList;
    }

    //使用java8 的新特性 写
    public static <T> List<List<T>> splitList(List<T> mlist, int num) {
        if (CollectionUtils.isEmpty(mlist) || num < 1) {
            return null;
        }
        return mlist.stream()
                .collect(Collectors.groupingBy(i -> mlist.indexOf(i) / num))
                .values()
                .stream()
                .collect(Collectors.toList());
    }
}
